package client.comm.baoding.ui

import android.view.View
import androidx.lifecycle.lifecycleScope
import client.comm.commlib.comm_ui.draw.SpaceItemDecoration
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.TxjlAdapter
import client.comm.baoding.api.bean.TxJl
import client.comm.baoding.databinding.ActivityTxjlBinding
import client.comm.baoding.ui.vm.TxjlViewModel
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.adapter.DtjlPagingAdapter
import client.comm.baoding.adapter.GpjlPagingAdapter
import client.comm.baoding.adapter.TxjlPagingAdapter
import client.comm.baoding.databinding.ActivityGpjlBinding
import client.comm.baoding.ui.vm.WdgpViewModel
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.network.data.PagingJsonResult
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class GpjlActivity : BaseMiddleActivity<WdgpViewModel, ActivityGpjlBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_gpjl
    }

    val adapter: GpjlPagingAdapter by lazy {
        GpjlPagingAdapter(this, mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyLayout.visibility = View.GONE
                }

            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }
        }
    }

    override fun initView() {
        binding?.apply {
            event = this@GpjlActivity
            vm = viewModel
            recyclerView.adapter = adapter.withLoadStateFooter(PagerFooterAdapter())
            recyclerView.addItemDecoration(SpaceItemDecoration(10))
            emptyLayout.setOnClickListener { adapter.refresh() }
            refreshLayout.setOnRefreshListener {
                adapter.refresh()
            }
        }
    }


    override fun initData() {
        lifecycleScope.launch {
            viewModel.pagingDataAuto {
                val ret = viewModel.server.zcjl(it, 10)
                PagingJsonResult(
                    list = ret.body()?.data?.record_list,
                    code = ret.body()?.code,
                    message = ret.body()?.message,
                    errorStr = ret.errorBody()?.string()
                )
            }.collect {
                adapter.submitData(it)
            }
        }
    }

    override fun initViewModel(): WdgpViewModel = createViewModel()

}